package mcom.xmks.bluetooth.mesh.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Locale;

import mcom.xmks.bluetooth.mesh.R;
import mcom.xmks.bluetooth.mesh.storage.GroupItem;

public class GroupListAdapter extends RecyclerView.Adapter<GroupListAdapter.ViewHolder> {
   private List<GroupItem> groupItemList=null;
   private OnClickListener listener;
   public GroupListAdapter(OnClickListener listener){
      this.listener=listener;
   }
   @NonNull
   @Override
   public  ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_grouplist, parent, false);
      return new ViewHolder(item);
   }

   @Override
   public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
      GroupItem groupItem=groupItemList.get(position);
      holder.groupName.setText(groupItem.getName());
      holder.groupAddress.setText(String.format(Locale.getDefault(),"Address:0x%04X",groupItem.getAddress()));
      holder.groupDeviceCount.setText(String.format(Locale.getDefault(),"%d Devices",
              groupItem.getNodeAddressItem()!=null?groupItem.getNodeAddressItem().size() : 0));
      holder.itemView.setOnClickListener(v->{
         if(listener!=null)
            listener.onClick(groupItem.getAddress(),groupItem.getName());
      });
      holder.itemView.setOnLongClickListener(v -> {
         if(listener!=null)
            listener.onLongClick(groupItem.getAddress(),groupItem.getName());
         return true;
      });
   }
   @Override
   public int getItemCount() {
      return groupItemList!=null?groupItemList.size():0;
   }
   public void loadAllGroups(List<GroupItem> items){
      this.groupItemList=items;
      notifyDataSetChanged();
   }
   class ViewHolder extends RecyclerView.ViewHolder{
      private TextView groupName,groupAddress,groupDeviceCount;
      public ViewHolder(@NonNull View itemView) {
         super(itemView);
         groupName=itemView.findViewById(R.id.tv_group_name);
         groupAddress=itemView.findViewById(R.id.tv_group_address);
         groupDeviceCount=itemView.findViewById(R.id.tv_group_device_count);
      }
   }
   public interface OnClickListener{
      void onClick(int groupAddress ,String groupName);
      void onLongClick(int groupAddress ,String groupName);
   }
}
